import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '../store'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/login',
  },
  {
    path: '/detail/:detailId',
    name: 'detail',
    meta: {
      auth: true,
      title: '详情',
    },
    component: () => import('../views/Detail.vue'),
  },
  {
    path: '/login',
    name: 'login',
    meta: {
      auth: false,
      title: '登陆',
    },
    component: () => import('../views/Login.vue'),
  },
  {
    path: '/layout',
    name: 'layout',
    component: () => import('../layout/index.vue'),
    children: [
      {
        path: 'home',
        name: 'home',
        meta: {
          auth: true, // 需要判断token才能进入页面
          title: '首页',
        },
        component: async () => {
          console.log('loading-true')
          const res = await import('../views/Home.vue')
          console.log('loading-false')
          return res
        },
      },
      {
        path: 'table',
        name: 'table',
        meta: {
          auth: true, // 需要判断token才能进入页面
          title: 'table',
        },
        component: async () => {
          return await import('../views/Table.vue')
        },
      },
    ],
  },
]

const routerPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return routerPush.call(this, location).catch((error) => error)
}

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes,
})

// 导航守卫
router.beforeResolve((to, from, next) => {
  console.log('导航守卫：', to.meta)
  if (to.meta.auth) {
    const token = store.state.token
    if (token) {
      next()
    } else {
      next({
        path: '/login',
        query: {
          // 带一个参数，知道用户是从哪个页面跳转到登陆页面的
          fullpath: to.fullPath,
        },
      })
    }
  } else {
    next()
  }
})

export default router
